//
//  YMSRefreshControl.swift
//  YMSWeibo
//
//  Created by 杨茂盛 on 2016/11/19.
//  Copyright © 2016年 杨茂盛. All rights reserved.
//

import UIKit
import SnapKit
//MARK: 定义下拉刷新控件的状态枚举
enum Refreshstate:Int{
    case Normol = 0
    case Already
    case Refreshing
}
private let refreshHeight:CGFloat = 60 //刷新控件的高度
class YMSRefreshControl: UIControl {

    //确定下拉状态
    var refreshState:Refreshstate = .Normol{
        didSet{
        
            switch refreshState {
            case .Normol:
                print("默认状态")
                tipLabel.text = "下拉刷新哦"
                indicator.stopAnimating()
                arrowIcon.isHidden = false
                //修改箭头的方向
                UIView.animate(withDuration: 0.25, animations: { 
                    //修改形变
                    self.arrowIcon.transform = CGAffineTransform.identity
                })
            case .Already:
                print("准备刷新")
                tipLabel.text = "松手刷新"
                //修改箭头的方向
                UIView.animate(withDuration: 0.25, animations: {
                    //修改形变
                    self.arrowIcon.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
            case .Refreshing:
                print("正在刷新")
                tipLabel.text = "正在刷新"
                indicator.startAnimating()
                arrowIcon.isHidden = true
                //数据请求完成之后就应该恢复默认状态
                
                //触发事件
                sendActions(for: .valueChanged)
            }
        }
    }
    //初始化的时候固定大小
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHeight, width: ScreenWidth, height: refreshHeight)
        super.init(frame: rect)
        self.backgroundColor = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 0.8123929795)
        self .setUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//-------------自定义的刷新控件如何监听tabeview的滚动从而做出反应------------------------
    //设置kvo观察就能监听到
    override func willMove(toSuperview newSuperview: UIView?) {
        //这个方法是子视图添加到父视图上会调用的方法,在这里拿到它的父类
        super.willMove(toSuperview: newSuperview)
        if let fatherView = newSuperview as? UIScrollView{
        
            //设置观察
            self.myScrollView = fatherView
            //添加观察
            self.myScrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
    }
    
    //MARK: 观察的监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        //拿到当前scrollview滚动的距离
        let offsetY = self.myScrollView?.contentOffset.y ?? 0 //初始是-64
        //控件的高度
        let targetOffsetY = -(self.myScrollView!.contentInset.top + refreshHeight) //初始是-124
        //print(offsetY,targetOffsetY)
        
        
        if self.myScrollView!.isDragging {
            //正在拖动的时候,判断状态
            
            if refreshState == .Normol && offsetY < targetOffsetY {
                //如果拖动的距离大于 控件的高度 -200 -124 那么就说明控件被拖出导航栏并且超出
                //控件要准备刷新了
                refreshState = .Already
            }else if refreshState == .Already && offsetY > targetOffsetY{
            //如果控件已经准备刷新了,但是拖动的距离大于小于控件的高度,那么说明控件没有被完全拉下来,那么就恢复到默认状态
                refreshState = .Normol
            }
        }else{
            //停止拖动或者准备刷新的状态->正在刷新
            if refreshState == .Already {
            //当状态为准备刷新的时候,并且手指离开了屏幕,那么就设置为属性刷新状态
                refreshState = .Refreshing
            }
        }
    }
    
    func endRefreshing(){
        //将statue修改为normoal状态
        refreshState = .Normol
    }
    
    //搭建界面
    private func setUI(){
        //添加控件
        addSubview(backImageView)
        self.addSubview(tipLabel)
        self.addSubview(arrowIcon)
        self.addSubview(indicator)
        //布局
        backImageView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
        }

        tipLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
            
            arrowIcon.snp.makeConstraints({ (make) in
                make.right.equalTo(tipLabel.snp.left).offset(-5)
                make.centerY.equalTo(tipLabel)
                
                indicator.snp.makeConstraints({ (make) in
                    make.center.equalTo(arrowIcon)
                })
            })
        }
    }
    
    //懒加载控件
    //显示的文字
    private lazy var tipLabel :UILabel = {
        let myLabel = UILabel()
        myLabel.text = "快拉我拉我"
        myLabel.textColor = #colorLiteral(red: 0.8078431487, green: 0.02745098062, blue: 0.3333333433, alpha: 1)
        return myLabel
    }()
    //显示的图片
    private lazy var arrowIcon :UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    //指示器
    private lazy var indicator:UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle:.white)
    //scrollview
    var myScrollView :UIScrollView?
    private lazy var backImageView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))

    
    deinit {
        //移除监听
        myScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
